using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;

using WMOSSExperts.Fields;

namespace WMOSSExperts.WebControls
{

    [CLSCompliant(false)]
    public class RelatedLookupLinksFieldEditor : UserControl, IFieldEditor
    {
        #region "Interface element defintion"
        protected CheckBox ChkShowInDisplayForm;
        protected CheckBoxList ChkRelatedLists;
        #endregion
           
        #region IFieldEditor Members

        public bool DisplayAsNewSection
        {
            get { return false; }
        }

        public void InitializeWithField(SPField field)
        {
            if (this.IsPostBack) return;

            if (field != null)
            {
                //Read the reverseLookupField
                RelatedLookupLinksField relatedField = (field as RelatedLookupLinksField);
                //Read value to Show in display form
                ChkShowInDisplayForm.Checked = relatedField.ShowInDisplayForm.HasValue ? relatedField.ShowInDisplayForm.Value : false;

                //Read related lists to display
                List<RelatedLookupLinksValue> relatedLists = relatedField.GetRelatedLists(true);
                foreach (RelatedLookupLinksValue relatedList in relatedLists)
                {
                    ListItem item = new ListItem(relatedList.ChildList, relatedList.ReverseLookupId.ToString());
                    item.Selected = relatedList.DisplayChildItems;
                    item.Attributes.Add("class", "ms-authoringcontrols");
                    ChkRelatedLists.Items.Add(item);
                }
            }

        }

        public void OnSaveChange(SPField field, bool isNewField)
        {
            RelatedLookupLinksField relatedField = (field as RelatedLookupLinksField);

            //Read value to Show in display form
            relatedField.ShowInDisplayForm = ChkShowInDisplayForm.Checked;

            //Read value from display sourceList configuration
            //and reset reverseLookupField configuration
            SortedList<Guid, Boolean> relatedLists = new SortedList<Guid, bool>();
            foreach (ListItem item in ChkRelatedLists.Items)
            {
                relatedLists.Add(new Guid(item.Value), item.Selected);
            }
            relatedField.SetDisplayLists(relatedLists);

        }


        #endregion
    }
}
